
function KUploadButton(options) {
	this.init(options);
}
_extend(KUploadButton, {
	init : function(options) {
		var self = this,
			button = K(options.button),
			fieldName = options.fieldName || 'file',
			url = options.url || '',
			title = button.text(),
			extraParams = options.extraParams || {},
			cls = button[0].className || '';
		options.afterError = options.afterError || function(str) {
			alert(str);
		};

		var hiddenElements = [];
		for(var k in extraParams){
			hiddenElements.push('<input type="hidden" name="' + k + '" value="' + extraParams[k] + '" />');
		}

		var html = [
			//'<div class="ke-inline-block ' + cls + '">',
			('<div class="ke-upload-area">'),
			//'<span class="ke-button-common">',
			hiddenElements.join(''),
			'<button type="button" class="ke-button">' + title + '</button>',
			//'<input type="button" class="ke-button-common ke-button" value="' + title + '" />',
			'</span>',
			'<input type="file" class="ke-upload-file" name="' + fieldName + '" tabindex="-1" />',
			'</div>'].join('');

		var div = K(html, button.doc);
		button.hide();
		button.before(div);

		self.div = div;
		self.button = button;
		//self.iframe = options.target ? K('iframe[name="' + target + '"]') : K('iframe', div);
		//self.form = options.form ? K(options.form) : K('form', div);
		self.fileBox = K('.ke-upload-file', div);
		//var width = options.width || K('.ke-button-common', div).width();
		//K('.ke-upload-area', div).width(width);
		self.options = options;
	},
	submit : function() {
		var self = this;
        var form = new FormData(),
            url = self.options.url, //服务器上传地址
            file = self.fileBox[0].files;
        form.append(self.options.fieldName, file[0]);
        var xhr = new XMLHttpRequest();
        xhr.open("POST", url, true);
        xhr.addEventListener("readystatechange", function() {
            var result = xhr;
            if (result.status != 200) {
                self.options.afterError.call(self, result.response);
            }else if (result.readyState == 4) {
                var data = K.json(_unescape(result.response));
                self.options.afterUpload.call(self, data);
            }
        });
        xhr.send(form);
		return self;
	},
	remove : function() {
		var self = this;
		if (self.fileBox) {
			self.fileBox.unbind();
		}
		// Bugfix: [IE] 上传图片后，进度条一直处于加载状态。
		//self.iframe[0].src = 'javascript:false';
		self.iframe.remove();
		self.div.remove();
		self.button.show();
		return self;
	}
});

function _uploadbutton(options) {
	return new KUploadButton(options);
}

K.UploadButtonClass = KUploadButton;
K.uploadbutton = _uploadbutton;

